map.SplitMergeTool = {
  splitLines: [], //绘制的线条
  cutLine: null,//拆分的线
  wallFeature: null,//拆分生成的墙，是拆分线的缓冲
  polygonDraws: [], //绘制的面
  wallWidth: 0.22, //墙体厚度
  roomSource: null, //房间信息的源-用于还原
  needAddFeatures: [],//临时存放需要更新的房间信息
  status: false, //是否进入到拆分状态
  selectFeature: null, //当次点选的房间-随着功能的增加，该属性逐步废止。
  drawFeatures: null,
  isEnableClick: true,
  mode: 'normal',//编辑模式  normal正常,split分割,merge合并
  mapContainer: null,
  option:{},//外部接口传入的相关参数
  drawObj: {
    draw: null,
    init: function (option) {
      if (this.draw === null) {
        const definedMode = {
          polygon: true,
          trash: true,
          line_string: true,
          point: false
        }

        this.draw = new MapboxDraw({
          displayControlsDefault: false,
          // Select which mapbox-gl-draw control buttons to add to the map.
          controls: definedMode,
          // Set mapbox-gl-draw to draw by default.
          // The user does not have to click the polygon control button first.
          defaultMode: 'simple_select'
        })
      }
      map.addControl(this.draw)
      map.SplitMergeTool.setChangeMode(option)
      map.on('draw.create', this.createFun)
      map.on('draw.delete', this.deleteFun)
      map.on('draw.update', this.updateFun)
    },
    createFun: function (e) {
      const geometry = e.features[0].geometry

      let result = {}

      if (geometry.type == 'LineString') {
        map.SplitMergeTool.splitLines.push(e.features[0])
        if (map.SplitMergeTool.splitLines.length > 1) {
          map.SplitMergeTool.drawObj.clearLine(1)
          console.log('当前只支持一条分割线，请重新绘制分割线!')
          result = { 'result': 'fail', 'msg': '当前只支持一条分割线，请重新绘制分割线!', 'code': '001', 'obj': {} }
        } else {
          result = { 'result': 'ok', 'msg': '绘制成功', 'code': '0', 'obj': { 'LineString': e.features[0] } }
        }
        if (typeof diyoption.drawCreate === 'function') {
          diyoption.drawCreate(result)
        }

      } else if (geometry.type == 'Polygon') {
        map.SplitMergeTool.polygonDraws.push(e.features[0])
        if (map.SplitMergeTool.polygonDraws.length > 1) {
          map.SplitMergeTool.drawObj.clearPolygon(1)
          console.log('当前只支持绘制单个合并，请重新绘制!')
          result = { 'result': 'fail', 'msg': '当前只支持绘制单个合并，请重新绘制!', 'code': '002', 'obj': { 'Polygon': e.features[0] } }
        } else {
          result = { 'result': 'ok', 'msg': '绘制成功', 'code': '0', 'obj': { 'Polygon': e.features[0] } }
        }
        if (typeof diyoption.drawCreate === 'function') {
          diyoption.drawCreate(result)
        }

      }
    },
    clearPolygon: function (index) {
      /*清除指定下标之后的绘制面*/
      let tarindex = 0

      let isClearAll = true

      if (typeof index === 'number') {
        if (map.SplitMergeTool.polygonDraws.length > index) {
          tarindex = index
          isClearAll = false
        } else {
          return
        }
      }
      for (let i = tarindex; i < map.SplitMergeTool.polygonDraws.length; i++) {
        this.draw.delete(map.SplitMergeTool.polygonDraws[i].id)
      }
      if (isClearAll) {
        map.SplitMergeTool.polygonDraws = []
      } else {
        map.SplitMergeTool.polygonDraws.splice(index, 1)
      }
    },
    deleteLineById(lineId, IsDrawDelete) {
      for (let i = 0; i < map.SplitMergeTool.splitLines.length; i++) {
        if (map.SplitMergeTool.splitLines[i].id === lineId) {
          if (IsDrawDelete && IsDrawDelete === true) {
            this.draw.delete(map.SplitMergeTool.splitLines[i].id)
          }
          map.SplitMergeTool.splitLines.splice(i, 1)
          i--
        }
      }
    },
    deletePolygonById(polygonId, IsDrawDelete) {
      for (let i = 0; i < map.SplitMergeTool.polygonDraws.length; i++) {
        if (map.SplitMergeTool.polygonDraws[i].id === polygonId) {
          if (IsDrawDelete && IsDrawDelete === true) {
            this.draw.delete(map.SplitMergeTool.polygonDraws[i].id)
          }
          map.SplitMergeTool.polygonDraws.splice(i, 1)
          i--
        }
      }
    },
    clearLine: function (index) {
      /*清除指定下标之后的绘制线*/
      let tarindex = 0

      let isClearAll = true

      if (typeof index === 'number') {
        if (map.SplitMergeTool.splitLines.length > index) {
          tarindex = index
          isClearAll = false
        } else {
          return
        }
      }
      for (let i = tarindex; i < map.SplitMergeTool.splitLines.length; i++) {
        this.draw.delete(map.SplitMergeTool.splitLines[i].id)
      }
      if (isClearAll) {
        map.SplitMergeTool.splitLines = []
      } else {
        map.SplitMergeTool.splitLines.splice(index, 1)
      }
    },
    deleteFun: function (e) {
      let result = {}

      const geometry = e.features[0].geometry

      if (geometry.type == 'LineString') {
        map.SplitMergeTool.drawObj.deleteLineById(e.features[0].id, false)
        result = { 'result': 'ok', 'msg': '绘制线删除!', 'code': '0', 'obj': { 'LineString': e.features[0] } }
      } else if (geometry.type == 'Polygon') {
        map.SplitMergeTool.drawObj.deletePolygonById(e.features[0].id, false)
        result = { 'result': 'ok', 'msg': '绘制面删除!', 'code': '0', 'obj': { 'Polygon': e.features[0] } }
      }
      if (typeof diyoption.drawDelete === 'function') {
        diyoption.drawDelete(result)
      }

    },
    updateFun: function (e) {
      let result = {}

      const geometry = e.features[0].geometry

      if (geometry.type == 'LineString') {
        for (var i = 0; i < map.SplitMergeTool.splitLines.length; i++) {
          if (map.SplitMergeTool.splitLines[i].id === e.features[0].id) {
            map.SplitMergeTool.splitLines.splice(i, 1, e.features[0])
            break
          }
        }
        result = { 'result': 'ok', 'msg': '绘制线修改!', 'code': '0', 'obj': { 'LineString': e.features[0] } }
      } else if (geometry.type == 'Polygon') {
        for (var i = 0; i < map.SplitMergeTool.polygonDraws.length; i++) {
          if (map.SplitMergeTool.polygonDraws[i].id === e.features[0].id) {
            map.SplitMergeTool.polygonDraws.splice(i, 1, e.features[0])
            break
          }
        }
        result = { 'result': 'ok', 'msg': '绘制面修改!', 'code': '0', 'obj': { 'Polygon': e.features[0] } }
      }
      if (typeof diyoption.drawUpdate === 'function') {
        diyoption.drawUpdate(result)
      }
    }
  },
  // 设置切割模式
  setSplitMode: function () {
    if (!this.status) {
      console.log('请先进入拆分合并模式（先执行SplitMergeTool.open()）!')
      return { 'result': 'fail', 'msg': '请先打开/进入拆分合并模式!', 'code': '003', 'obj': { 'mode': this.mode } }
    }
    if (this.mode != 'split') {
      this.setChangeMode({ 'mode': 'split' })
    }
    this.drawObj.draw.changeMode('draw_line_string')
    return { 'result': 'ok', 'msg': '操作成功！', 'code': '0', 'obj': { 'model': this.mode } }
  },
  // 设置合并模式
  setMergeMode: function (isOnlaySelect) {
    if (!this.status) {
      console.log('请先进入拆分合并模式（先执行SplitMergeTool.open()）!')
      return { 'result': 'fail', 'msg': '请先打开/进入拆分合并模式!', 'code': '003', 'obj': { 'mode': this.mode } }
    }
    if (this.mode != 'merge') {
      this.setChangeMode({ 'mode': 'merge' })
    }
    if (!isOnlaySelect) {
      this.drawObj.draw.changeMode('draw_polygon')
    }
    return { 'result': 'ok', 'msg': '操作成功！', 'code': '0', 'obj': { 'model': this.mode } }
  },
  // 设置合并模式还是切割模式
  setChangeMode: function (option) {
    if (!this.status) {
      console.log('请先进入拆分合并模式（先执行SplitMergeTool.open()）!')
      return { 'result': 'fail', 'msg': '请先打开/进入拆分合并模式!', 'code': '003', 'obj': { 'mode': this.mode } }
    }
    if (typeof option === 'object' && option.mode) {
      if (option.mode == 'split' || this.mode != 'merge') {
        if (option.mode == 'split' && this.mode != 'split') {
          this.mode = 'split'
          this.cancel()
          /*  this.drawObj.draw.options.controls.polygon=false;
            this.drawObj.draw.options.controls.line_string=true;
            map.removeControl(this.drawObj.draw);
            map.addControl(this.drawObj.draw);*/
          //  this.drawObj.draw.changeMode("draw_line_string");
          //   $(".mapbox-gl-draw_ctrl-draw-btn").css("display","none");
        } else if (option.mode == 'merge' && this.mode != 'merge') {
          this.mode = 'merge'
          this.cancel()
          /*  this.drawObj.draw.options.controls.polygon=true;
            this.drawObj.draw.options.controls.line_string=false;
            map.removeControl(this.drawObj.draw);
            map.addControl(this.drawObj.draw);*/
          //  this.drawObj.draw.changeMode("draw_polygon");
          //  $(".mapbox-gl-draw_ctrl-draw-btn").css("display","none");
        }
      } else {
        option.mode = 'split'
        this.setChangeMode(option)
      }
    } else {
      option = {}
      if (this.mode == 'split') {
        option.mode = 'merge'
        this.setChangeMode(option)
      } else if (this.mode == 'merge') {
        option.mode = 'split'
        this.setChangeMode(option)
      } else {
        option.mode = 'split'
        this.setChangeMode(option)
      }
    }

    return { 'result': 'ok', 'msg': '模式切换成功！', 'code': '0', 'obj': { 'model': this.mode } }
  },
  // 改变模式
  changeMode2(option) {
    if (!this.status) {
      console.log('请先进入拆分合并模式（先执行SplitMergeTool.open()）!')
      return { 'result': 'fail', 'msg': '请先打开/进入拆分合并模式!', 'code': '003', 'obj': { 'mode': this.mode } }
    }
    if (typeof option === 'object' && option.mode) {
      if (option.mode == 'split' && this.mode != 'split') {
        this.mode = 'split'
        this.cancel()
        this.drawObj.draw.options.controls.polygon = false
        this.drawObj.draw.options.controls.line_string = true
        map.removeControl(this.drawObj.draw)
        map.addControl(this.drawObj.draw)
      } else if (option.mode == 'merge' && this.mode != 'merge') {
        this.mode = 'merge'
        this.cancel()
        this.drawObj.draw.options.controls.polygon = true
        this.drawObj.draw.options.controls.line_string = false
        map.removeControl(this.drawObj.draw)
        map.addControl(this.drawObj.draw)
      } else if (this.mode == 'split') {
        option.mode = 'merge'
        this.changeMode(option)
      } else if (this.mode == 'merge') {
        option.mode = 'split'
        this.changeMode(option)
      } else { }
    } else {
      option = {}
      if (this.mode == 'split') {
        option.mode = 'merge'
        this.changeMode(option)
      } else if (this.mode == 'merge') {
        option.mode = 'split'
        this.changeMode(option)
      }
    }

    return { 'result': 'ok', 'msg': '模式切换成功！', 'code': '0', 'obj': { 'model': this.mode } }
  },
  style: function (style) {//设置编辑的样式
    this.paint = style
  },
  open: function (option) { //1.打开编辑
    if (this.status) {
      return { 'result': 'ok', 'msg': '您已经打开拆分合并开关，不需要再次打开！', 'code': '0', 'obj': { 'status': this.status } }
    }
    this.option = option
    if (typeof option === 'object') {
      diyoption = $.extend(true, diyoption, option)
    }
    if (!this.status) {
      this.status = true
      this.init(diyoption)
    }
    map.SplitMergeTool.drawObj.init(diyoption)
    map.on('click', this.click)
    map.on('contextmenu', this.contextmenu)
    map.SplitMergeTool.mapContainer = map.getCanvasContainer()
    map.SplitMergeTool.mapContainer.addEventListener('keydown', this.keydown)
    //map.draw.init();//初始化绘制资源
    return { 'result': 'ok', 'msg': '开启成功', 'code': '0', 'obj': { 'status': this.status } }
  },
  //初始化编辑资源
  init: function () {//2.初始化编辑层
    //判断是否有编辑层，没有则添加
    if (!map.getSource('editDrawFeature')) {
      const drawFeatureCollection = { 'type': 'FeatureCollection', 'features': [] }

      map.addSource('editDrawFeature', { 'type': 'geojson', 'data': drawFeatureCollection })
      //面层选中后的样式
      map.addLayer({
        id: 'editDrawFeature',
        type: 'fill',
        source: 'editDrawFeature',
        paint: {
          'fill-color': 'blue',
          'fill-opacity': 0.2 // 透明度
        },
        filter: ['in', '$type', 'Polygon']
      })
      //面层的线-选中样式
      map.addLayer({
        id: 'editDrawFeaturesLine',
        type: 'line',
        source: 'editDrawFeature',
        layout: {
          'line-cap': 'round',
          'line-join': 'round'
        },
        paint: {
          'line-color': '#ff0000',
          'line-width': 2
        },
        filter: ['in', '$type', 'Polygon']
      })
      map.addLayer({
        id: 'showEditDrawFeature',
        type: 'fill',
        source: 'room',
        paint: {
          'fill-color': '#afabab',
          'fill-opacity': 0.8 // 透明度 diyType
        },
        filter: ['in', ['get', 'operationType'], 'add']

      })
      map.addLayer({
        id: 'showEditDrawFeatureLineAdd',
        type: 'line',
        source: 'room',
        paint: {
          'line-color': '#808080',
          'line-width': 2
        },
        filter: ['in', ['get', 'operationType'], 'add']

      })

      // 绘制后的面、线、点资源
      if (!map.getSource('editDrawFeatureCollection')) {
        map.addSource('editDrawFeatureCollection', { 'type': 'geojson', 'data': drawFeatureCollection })
      }
      // 绘制后的面、线、点层-拆分预览
      if (!map.getLayer('editDrawFeaturesPolygon')) {
        //面要素的 面样式
        map.addLayer({
          id: 'editDrawFeaturesPolygon',
          type: 'fill',
          source: 'editDrawFeatureCollection',
          paint: {
            'fill-color': 'blue',
            'fill-opacity': 0.1 // 透明度
          },
          filter: ['in', '$type', 'Polygon']
        })
        //面要素的 线样式
        map.addLayer({
          id: 'editDrawFeaturesPolygon_line',
          type: 'line',
          source: 'editDrawFeatureCollection',
          layout: {
            'line-cap': 'round',
            'line-join': 'round'
          },
          paint: {
            'line-color': '#ff0000',
            'line-width': 2
          },
          filter: ['in', '$type', 'Polygon']
        })
        //面要素的 点样式
        /*       map.addLayer({
                   id: 'drawFeaturesPolygon_point',
                   type: 'circle',
                   source: 'editDrawFeatureCollection',
                   paint: {
                       'circle-radius': 5,
                       'circle-color': '#ff0000'
                   },
                   filter: ['in', '$type', 'Polygon']
               });
           }
           if (!map.getLayer('editDrawFeaturesLineString')) {
               //线要素的 线样式
               map.addLayer({
                   id: 'editDrawFeaturesLineString',
                   type: 'line',
                   source: 'editDrawFeatureCollection',
                   layout: {
                       'line-cap': 'round',
                       'line-join': 'round'
                   },
                   paint: {
                       'line-color': '#ff0000',
                       'line-width': 2
                   },
                   filter: ['in', '$type', 'LineString']
               });

           */
      }

    }
  },
  // 右击删除
  contextmenu: function (e) {
    const mapDraw = map.SplitMergeTool.drawObj

    if (mapDraw.draw !== null) {
      const selectIds = mapDraw.draw.getSelectedIds()

      for (let i = 0; i < selectIds.length; i++) {
        if (map.SplitMergeTool.mode == 'split') {
          mapDraw.deleteLineById(selectIds[i], true)
        } else if (map.SplitMergeTool.mode == 'merge') {
          mapDraw.deletePolygonById(selectIds[i], true)
        }
      }
    }
  },
  // 监听删除键
  keydown: function (e) {
    if (e.keyCode === 46) {
      const mapDraw = map.SplitMergeTool.drawObj

      if (mapDraw.draw !== null) {
        const selectIds = mapDraw.draw.getSelectedIds()

        for (let i = 0; i < selectIds.length; i++) {
          if (map.SplitMergeTool.mode == 'split') {
            mapDraw.deleteLineById(selectIds[i], true)
          } else if (map.SplitMergeTool.mode == 'merge') {
            mapDraw.deletePolygonById(selectIds[i], true)
          }
        }
      }
    }
  },
  // 启用点击
  setEnableClick: function (isEnableClick) {
    if (typeof isEnableClick === 'boolean') {
      this.isEnableClick = isEnableClick
    } else {
      this.isEnableClick = !isEnableClick
    }
  },
  click: function (e) {//3.点击选中要编辑的要素
    //如果是点在了正在编辑的图形上，正常操作
    if (!this.SplitMergeTool.isEnableClick) {
      return
    }
    if(this.SplitMergeTool.option.selectLockModel && String(this.SplitMergeTool.option.selectLockModel.selectLockModel) == 'true') {
      //  shgis.SplitMergeTool.setEnableClick(false);
      if(this.SplitMergeTool.selectFeature === null) {
        return null
      }
    }
    const editLayers = map.queryRenderedFeatures(e.point, { layers: ['editDrawFeature'] })

    if (editLayers.length > 0) {
      if (this.SplitMergeTool.mode == 'merge') {
        const source = map.getSource('editDrawFeature')._data

        for (let i = 0; i < source.features.length; i++) {
          const curFeatures = source.features[i]

          if (curFeatures.properties.id == editLayers[0].properties.id) {
            source.features.splice(i, 1)
            break
          }
        }
        map.getSource('editDrawFeature').setData(source)
        return
      }
      return

    }
    //选中编辑的要素
    const editLayer = ['room']

    const features = map.queryRenderedFeatures([[e.point.x - 5, e.point.y - 5], [e.point.x + 5, e.point.y + 5]], { layers: editLayer })

    if (features.length == 0) {
      return
    }//如果点中了空白区域
    //获取选中的要素
    map.getSource(map.getLayer('room').source)._data.features.forEach(f => {
      if (f.properties.id == features[0].properties.id) {
        this.SplitMergeTool.selectFeature = JSON.parse(JSON.stringify(f))//pdf服务读不到gid只有用id
      }
    })
    if (this.SplitMergeTool.selectFeature === null) {
      return
    }
    const source = map.getSource('editDrawFeature')._data

    if (!source.features) {
      source.features = []
    }
    if (this.SplitMergeTool.mode == 'merge') {
      source.features.push(this.SplitMergeTool.selectFeature)
    } else {
      source.features[0] = this.SplitMergeTool.selectFeature
    }
    map.getSource('editDrawFeature').setData(source)
  },
  unionFeatures: function () {
    map.SplitMergeTool.cutLine = null
    map.SplitMergeTool.wallFeature = null
    if (this.mode != 'merge') {
      console.log('当前模式不是合并模式，无法进行合并预览!')
      return { 'result': 'fail', 'msg': '当前模式不是合并模式，无法进行合并预览!', 'code': '004', 'obj': {} }
    }
    const selectRes = this.getSelectFeatures()

    const selectFeatures = selectRes.obj.selectFeatures

    if (selectFeatures.length < 2) {
      console.log('没有要合并的房间，请至少选中两个相连的房间进行合并!')
      return { 'result': 'fail', 'msg': '没有要合并的房间，请至少选中两个相连的房间进行合并!', 'code': '005', 'obj': {} }
    }
    const source = map.getSource('room')._data

    if (this.roomSource === null) {
      // $.extend() 深度合并后面两个参数对象
      this.roomSource = $.extend(true, {}, source)
    }
    let unionPolygon = selectFeatures[0]
    const copyPolygon = $.extend(true, {}, unionPolygon)
    const fjhs = []
    const fjmcs = []
    const ids = []

    let drawFeatures = this.drawFeatures

    if (drawFeatures === null) {
      this.drawFeatures = { 'type': 'FeatureCollection', 'features': [] }
      drawFeatures = this.drawFeatures
    }

    for (var i = 0; i < selectFeatures.length; i++) {
      if (selectFeatures[i]['properties'].operationType == 'delete' || selectFeatures[i]['properties'].operationType == 'add') {
        continue
      }
      unionPolygon = union(unionPolygon, selectFeatures[i])
      fjhs.push(selectFeatures[i]['properties'].fjh)
      fjmcs.push(selectFeatures[i]['properties'].fjmc)
      ids.push(selectFeatures[i]['properties'].id)
      selectFeatures[i].geometry.coordinates = [[[0, 0], [0, 0], [0, 0], [0, 0]]]
      selectFeatures[i]['properties'].operationType = 'delete'
      selectFeatures[i].properties.tempId = selectFeatures[i]['properties'].id
      drawFeatures.features.push(selectFeatures[i])

    }
    if (this.polygonDraws.length > 0) {
      unionPolygon = union(unionPolygon, this.polygonDraws[0])
    }
    if (unionPolygon.geometry.type == 'Polygon') {
      copyPolygon.properties.fjh = fjhs.join('@')
      copyPolygon.properties.fjmc = fjmcs.join('@')
      copyPolygon.properties.id = ids.join('')
      copyPolygon.id = ids.join('')
      copyPolygon.geometry = unionPolygon.geometry
      copyPolygon.properties.operationType = 'add'
      copyPolygon.properties.tempId = copyPolygon.id
      drawFeatures.features.push(copyPolygon)
      //   map.getSource('editDrawFeatureCollection').setData(drawFeatures);
      map.getSource('editDrawFeature').setData({ 'type': 'FeatureCollection', 'features': [] })
      for (let x = 0; x < source.features.length; x++) {
        const curFe = source.features[x]

        for (var i = 0; i < selectFeatures.length; i++) {
          if (curFe.properties.id == selectFeatures[i].properties.id) {
            source.features.splice(x, 1)
            x--
          }
        }
      }
      source.features.push(copyPolygon)
      map.getSource('room').setData(source)
      this.drawObj.clearPolygon()
    } else {
      console.log('要合并的房间之间需要有连接（接触）的地方，例如两房间紧密接触或有重合的地方！')
      return { 'result': 'fail', 'msg': '要合并的房间之间需要有连接（接触）的地方，例如两房间紧密接触或有重合的地方！', 'code': '006', 'obj': {} }
    }
    const mapid = selectFeatures[0].properties.mapid.substring(0,7)

    const needDelWall = []//存放需要删减的墙体数据（即合并的房屋完整包含该墙体）

    const needUpdateWalltemp = []//临时存放可能需要修改的墙体数据

    const updateSourceInfo = {}//可能需要修改墙体的原始数据

    const needUpdateWall = []//经过面积占比等条件过滤后需要修改的墙体

    $.ajax({
      url: mapserver + '/data/getAllBaseInfo',
      type: 'POST',
      async:false,
      data: {layer: 'indoorwall', mapid:mapid},
      dataType: 'json',
      success: function (res) {
        console.log(res)
        for(const index in res) {
          const obj = res[index]

          const geom = JSON.parse(obj.geojson)

          const feature = {
            'type': 'Feature',
            'properties': {id:obj.id,gid:obj.gid},
            'geometry':geom
          }

          const isIntersect = intersect(feature,copyPolygon)

          if (isIntersect) {
            const iscd = difference(feature,copyPolygon)

            if(iscd) {
              iscd.properties = {id: obj.id, gid: obj.gid}
              needUpdateWalltemp.push(iscd)
              updateSourceInfo['wall' + obj.gid] = feature
            }else{
              needDelWall.push(feature)
            }
          }

          /*     //判断墙体是否包含在合并的图形内
                if(geom.type=='MultiPolygon'){
                  var  mycoordinates=geom.coordinates;
                  for(var n=0; n<mycoordinates.length;n++){
                   var curFea=turf.polygon(mycoordinates[n]);
                   var isbh=booleanContains(copyPolygon,curFea);
                   if(isbh){
                     needDelWall.push(feature);
                     break;
                   }
                 }
               }else{
                 var isbh=booleanContains(copyPolygon,feature);
                 if(isbh){
                   needDelWall.push(feature);
                   continue;
                 }
               }
               var isIntersect = intersect(feature,copyPolygon);
               if (isIntersect) {
                 var iscd = difference(feature,copyPolygon);
                 iscd.properties={id:obj.id,gid:obj.gid};
                 needUpdateWall.push(iscd);
               }*/
        }

        for(const i in needUpdateWalltemp) {
          const curWallInfo = needUpdateWalltemp[i]

          const gid = curWallInfo.properties.gid

          const sourceData = updateSourceInfo['wall' + gid]

          const updateArea = area(curWallInfo)

          const sourceArea = area(sourceData)

          const bfb = updateArea / sourceArea
          //墙体修改后的面积比原来缩小0.85的才算有效修改

          if(bfb < 0.85) {
            //墙体改后的面积比原始墙体面积比低于0.25（即删减了3/4）我们就认为该墙应该比删除了
            if(bfb < 0.25) {
              needDelWall.push(sourceData)
            }else{
              //墙体改动面积占比为大于等于0.25且小于等于0.85 的，我们认为该墙体是切除部分，保留部分
              needUpdateWall.push(curWallInfo)
            }
          }
        }

        if(map.SplitMergeTool.wallFeature) {
          map.SplitMergeTool.wallFeature.needDelWall = needDelWall
          map.SplitMergeTool.wallFeature.needUpdateWall = needUpdateWall
        }else{
          map.SplitMergeTool.wallFeature = {needDelWall:needDelWall,needUpdateWall:needUpdateWall}
        }

      }
    })

    return { 'result': 'ok', 'msg': '合并成功！', 'code': '0', 'obj': { 'unionPolygon': copyPolygon } }


  },
  splitAndGetFeatures: function () {
    map.SplitMergeTool.cutLine = null
    map.SplitMergeTool.wallFeature = null
    if (this.mode != 'split') {
      console.log('当前模式不是拆分模式，无法进行拆分预览!')
      return { 'result': 'fail', 'msg': '当前模式不是拆分模式，无法进行拆分预览!', 'code': '007', 'obj': {} }
    }
    if (this.splitLines.length == 0 || this.selectFeature === null) {
      console.log('未选中所要拆分的房间或未绘制拆分线!')
      return { 'result': 'fail', 'msg': '未选中所要拆分的房间或未绘制拆分线!', 'code': '008', 'obj': {} }
    }
    const source = map.getSource('room')._data

    if (this.roomSource === null) {
      this.roomSource = $.extend(true, {}, source)
    }
    const clipLineFeature = this.splitLines[0]
    const selectFeature = this.selectFeature

    let splitFeatures = null
    const draw = this.drawObj.draw

    let drawFeatures = this.drawFeatures

    if (drawFeatures === null) {
      this.drawFeatures = { 'type': 'FeatureCollection', 'features': [] }
      drawFeatures = this.drawFeatures
    }
    try {
      //获取切割点
      const cutPoint = lineIntersect(selectFeature, clipLineFeature)

      var cutLine = lineSlice(cutPoint.features[0], cutPoint.features[1], clipLineFeature)

      let wallWidth = 0.22

      if(map.SplitMergeTool.wallWidth) {
        wallWidth = Number(map.SplitMergeTool.wallWidth)
      }
      wallWidth = wallWidth / 2000
      const cutWallBuffered = buffer(cutLine, wallWidth, {units: 'kilometers',steps:0})
      var wallFeature = intersect(selectFeature, cutWallBuffered)

      if(wallFeature) {
        wallFeature = turf.multiPolygon([wallFeature.geometry.coordinates])
        wallFeature.properties.mapid = selectFeature.properties.mapid.substring(0,7)
        wallFeature.properties.wallwidth = wallWidth
        cutLine.properties.mapid = selectFeature.properties.mapid.substring(0,7)
        cutLine.properties.wallwidth = wallWidth
      }
      const clippedPolygon = geoUtil.polygonClipByLine(selectFeature, clipLineFeature)

      splitFeatures = clippedPolygon
      for (let i = 0; i < clippedPolygon.features.length; i++) {
        const curObj = $.extend(true, {}, selectFeature)

        const cordi = difference(clippedPolygon.features[i], cutWallBuffered)

        if(cordi) {
          curObj.geometry.coordinates = cordi.geometry.coordinates
        }else{
          curObj.geometry.coordinates = clippedPolygon.features[i].geometry.coordinates
        }
        if (i != 0) {
          curObj.id = curObj.id + 'split' + i
          curObj.properties['operationType'] = 'add'
          curObj.properties.tempId = curObj.id
          curObj.properties['id'] = curObj.id
        } else {
          curObj.properties['operationType'] = 'update'
          curObj.properties.tempId = curObj.id
        }
        drawFeatures.features.push(curObj)
        // draw.add(clippedPolygon.features[i])
        //  clipResultLayer.addLayer(newLayer);
      }
      // document.getElementById('msg').innerHTML = '<div style="color:#3fcf3f;">多边形裁剪成功</div>'
    } catch (error) {
      console.log('结果：' + error.state + '，错误原因：' + error.message)
      return { 'result': 'fail', 'msg': error.message, 'state': error.state, 'code': '009', 'obj': {} }
      /* document.getElementById('msg').innerHTML = '<div style="color:#ff0000;">' + error.state + ':</br>' +
           error.message + '</div>' */
    }
    map.getSource('editDrawFeatureCollection').setData(drawFeatures)

    this.drawObj.clearLine()
    map.getSource('editDrawFeature').setData({ 'type': 'FeatureCollection', 'features': [] })
    this.selectFeature = null
    this.splitLines = []
    map.SplitMergeTool.cutLine = cutLine
    map.SplitMergeTool.wallFeature = {'add':wallFeature}
    return { 'result': 'ok', 'msg': '拆分成功！', 'code': '0', 'obj': { 'splitFeatures': drawFeatures,'cutLine': cutLine,'wallFeature':wallFeature } }

  },
  cancel: function () {
    map.SplitMergeTool.cutLine = null
    map.SplitMergeTool.wallFeature = null
    if (!this.status) {
      console.log('请先进入拆分合并模式（先执行SplitMergeTool.open()）!')
      return { 'result': 'fail', 'msg': '请先打开/进入拆分合并模式!', 'code': '003', 'obj': { 'mode': this.mode } }
    }
    if (map.getSource('editDrawFeature')) {
      map.getSource('editDrawFeature').setData({ 'type': 'FeatureCollection', 'features': [] })
    }
    if (map.getSource('editDrawFeatureCollection')) {
      map.getSource('editDrawFeatureCollection').setData({ 'type': 'FeatureCollection', 'features': [] })
    }
    let source = map.getSource('room')._data

    if (this.roomSource !== null) {
      source = this.roomSource
      this.roomSource = null
    }
    if (source !== null) {
      for (let x = 0; x < source.features.length; x++) {
        const curFe = source.features[x]

        delete curFe.properties.operationType
      }
      map.getSource('room').setData(source)
    }

    this.drawObj.clearLine()
    this.drawObj.clearPolygon()
    this.selectFeature = null
    /*        this.splitLines = [];
            this.polygonDraws = [];*/
    this.drawFeatures = null
    this.needAddFeatures.splice(0, this.needAddFeatures.length)
    this.setEnableClick(true)
    return { 'result': 'ok', 'msg': '重置成功!', 'code': '0', 'obj': {} }
  },
  getSelectFeatures: function () {
    if (!this.status) {
      console.log('请先进入拆分合并模式（先执行SplitMergeTool.open()）!')
      return { 'result': 'fail', 'msg': '请先打开/进入拆分合并模式!', 'code': '003', 'obj': { 'mode': this.mode } }
    } else if (this.mode == 'merge' || this.mode == 'split') {
      return { 'result': 'ok', 'msg': '获取选中成功!', 'code': '0', 'obj': { 'selectFeatures': map.getSource('editDrawFeature')._data.features } }
    }
    return { 'result': 'ok', 'msg': '获取选中成功,但是模式不正确，所以获取为空!', 'code': '0', 'obj': { 'selectFeatures': [] } }

  },
  getBaseInfo: function () {
    const selectFes = this.getSelectFeatures()

    const res = { 'mode': this.mode, 'status': this.status, 'selectFeature': selectFes.obj.selectFeatures, 'drawFeatures': this.drawFeatures }

    return { 'result': 'ok', 'msg': '获取基础信息成功!', 'code': '0', 'obj': res }
  },
  save: function () {
    const sourceId = map.getLayer('room').source

    const source = map.getSource(sourceId)._data
    // 只支持geojsos

    if (map.getSource(sourceId).type.toLowerCase() != 'geojson') {
      if (typeof diyoption.getSaveResult === 'function') {
        diyoption.getSaveResult(json)
      }
    }
    const drawFeatures = this.drawFeatures
    const needAddFeatures = this.needAddFeatures
    const needUpdateFeatures = []

    if (this.mode == 'split') {
      for (let i = 0; i < drawFeatures.features.length; i++) {
        const curFeature = drawFeatures.features[i]

        if (curFeature.properties.operationType === 'add') {
          needAddFeatures.push(curFeature)
          continue
        }
        for (let n = 0; n < source.features.length; n++) {
          if (source.features[n].properties.id == curFeature.properties.id) {
            source.features[n] = curFeature
          }
        }
      }
    }
    const that = this

    const features = JSON.stringify(drawFeatures)

    let cutline = null

    let wallFeature = null

    if(map.SplitMergeTool.wallFeature) {
      cutline = JSON.stringify(map.SplitMergeTool.cutLine)
      wallFeature = JSON.stringify(map.SplitMergeTool.wallFeature)
    }
    $.ajax({
      url: mapserver + '/data/save',
      type: 'POST',
      data: { layer: sourceId, geojson: features,cutLine:cutline,wallFeature:wallFeature },
      dataType: 'json',
      success: function (json) {
        map.SplitMergeTool.cutLine = null
        map.SplitMergeTool.wallFeature = null
        if (json.code == 200 && json.data && json.data.length > 0) {
          that.roomSource = null
          json.data.forEach(e => {
            if (e.type == 'add' && that.mode == 'split') {
              for (var i = 0; i < that.needAddFeatures.length; i++) {
                if (e.tempId === that.needAddFeatures[i].properties.tempId) {
                  that.needAddFeatures[i].properties.mapid = e.mapid
                  that.needAddFeatures[i].properties.id = e.id
                  delete that.needAddFeatures[i].properties.operationType
                  source.features.push(that.needAddFeatures[i])
                  break
                }
              }
            } else if (e.type == 'add' && that.mode == 'merge') {
              for (var i = 0; i < source.features.length; i++) {
                if (source.features[i].properties.tempId === e.tempId) {
                  source.features[i].properties.mapid = e.mapid
                  source.features[i].properties.id = e.id
                  delete source.features[i].properties.operationType
                  break
                }
              }
            } else {
              /*       for(var i=0;i<source.features.length;i++){
                         if(source.features[i].id===e.id){
                             delete source.features[i].properties.operationType;
                             break;
                         }
                     }*/
            }

          })
          map.getSource(sourceId).setData(source)
          //json.data=drawFeatures;
          if (typeof diyoption.getSaveResult === 'function') {
            const res = { 'result': 'ok', 'msg': '保存成功!', 'code': '0', 'obj': { 'result': json } }

            diyoption.getSaveResult(res)
          }
        }
        that.cancel()
      },
      error: function (e) {
        console.log(e)
        map.SplitMergeTool.cutLine = null
        map.SplitMergeTool.wallFeature = null
        if (typeof diyoption.getSaveResult === 'function') {
          const res = { 'result': 'fail', 'msg': '保存失败!', 'code': '012', 'obj': { 'result': e } }

          diyoption.getSaveResult(json)
        }
      }
    })
  },
  updateFeature: function () {
    if (!this.status) {
      console.log('请先进入拆分合并模式（先执行SplitMergeTool.open()）!')
      return { 'result': 'fail', 'msg': '请先打开/进入拆分合并模式!', 'code': '003', 'obj': { 'mode': this.mode } }
    }
    if (!map.SplitMergeTool.drawObj.draw) {
      return { 'result': 'fail', 'msg': '初始化绘制工具失败!', 'code': '010', 'obj': {} }
    }
    if (this.drawFeatures === null) {
      let type = '合并'

      if (this.mode == 'split') {
        type = '拆分'
      }
      console.log('没有获取到' + type + '信息，请检查是否选中房间并执行了' + type + '的操作（如是否调用splitAndGetFeatures方法）!')
      return { 'result': 'fail', 'msg': '没有获取到' + type + '信息，请检查是否选中房间并执行了' + type + '预览的操作!', 'code': '011', 'obj': {} }
    }
    this.save()
  },
  openOrClose: function (option) {
    let status = ''

    if (this.status) {
      status = '关闭'
      return this.close()
    }
    status = '开启'
    return this.open(option)

    //return {"result": "ok", "msg": "拆分合并"+status+"成功!","code":"0","obj":{"status":this.status}};

  },
  close: function () {//5关闭编辑
    if (!this.status) {
      return { 'result': 'ok', 'msg': '您已经关闭拆分合并开关，不需要再次关闭！', 'code': '0', 'obj': { 'status': this.status } }
    }
    this.mode = 'normal'
    map.off('click', this.contextmenu)
    map.off('click', this.click)
    if (map.SplitMergeTool.mapContainer !== null) {
      map.SplitMergeTool.mapContainer.removeEventListener('keydown', this.keydown)
    }
    this.cancel()
    map.removeControl(this.drawObj.draw)
    this.drawObj.draw = null
    if (map.getLayer('editDrawFeature')) {
      map.removeLayer('editDrawFeature')
    }
    if (map.getLayer('showEditDrawFeature')) {
      map.removeLayer('showEditDrawFeature')
    }
    if (map.getLayer('showEditDrawFeatureLineAdd')) {
      map.removeLayer('showEditDrawFeatureLineAdd')
    }
    if (map.getLayer('showEditDrawFeaturesLine')) {
      map.removeLayer('showEditDrawFeaturesLine')
    }
    if (map.getLayer('editDrawFeaturesLine')) {
      map.removeLayer('editDrawFeaturesLine')
    }
    if (map.getLayer('editDrawFeaturesPolygon')) {
      map.removeLayer('editDrawFeaturesPolygon')
    }
    if (map.getLayer('editDrawFeaturesPolygon_line')) {
      map.removeLayer('editDrawFeaturesPolygon_line')
    }
    if (map.getSource('editDrawFeatureCollection')) {
      map.removeSource('editDrawFeatureCollection')
    }
    if (map.getSource('editDrawFeature')) {
      map.removeSource('editDrawFeature')
    }
    this.status = false
    return { 'result': 'ok', 'msg': '关闭成功', 'code': '0', 'obj': { 'status': this.status } }

  },
  deleteFeature: function () {//4-.正在编辑的要素，删除,当前是右键调用
    if (map.draw.drawFeature == undefined) {
      return
    }
    let exist = false

    for (let i = 0; i < map.draw.drawFeatures.length; i++) {
      if (map.draw.drawFeatures[i].properties.id == map.draw.drawFeature.properties.id) {
        if (map.draw.drawFeatures[i].properties.operationType == 'add') {
          map.draw.drawFeatures.splice(i, 1)
        } //删除新绘的要素，因为库没有，所以可直接删除
        else if (map.draw.drawFeatures[i].properties.operationType == 'update') {
          map.draw.drawFeatures[i].properties.operationType = 'delete'
        }//删除已有的要素，update改为delete,用于删除库里数据
        i = map.draw.drawFeatures.length//跳出循环
        exist = true
      }
    }
    if (!exist) { //不存在
      if (!map.draw.drawFeature.properties.operationType) {
        map.draw.drawFeature.properties['operationType'] = 'delete'
      }//如果要素是原有的，操作类型是删除
      map.draw.drawFeatures.push(indoorRotate(map.draw.drawFeature, true))//绘制要素放到集合里
    }

    //如果右键的要素是绘制的集合
    // for(var i=0;i<map.draw.drawFeatures.length;i++){
    //   if(map.draw.drawFeature.properties.id==map.draw.drawFeatures[i].properties.id) {
    //     if(map.draw.drawFeatures[i].properties.operationType=='add'){ map.draw.drawFeatures.splice(i,1);} //删除新绘的要素，因为库没有，所以可直接删除
    //     else if(map.draw.drawFeatures[i].properties.operationType=='update') { map.draw.drawFeatures[i].properties.operationType='delete'; }//删除已有的要素，update改为delete,用于删除库里数据
    //     i=map.draw.drawFeatures.length;//跳出循环
    //   };
    // }
    //更新资源层
    const sourceId = map.getLayer('room').source

    const source = map.getSource(sourceId)._data

    for (let i = 0; i < source.features.length; i++) {
      if (source.features[i].properties.id == map.draw.drawFeature.properties.id) {
        source.features.splice(i, 1)
        map.getSource(sourceId).setData(source)
        this.cancel()
        i = source.features.length
      }
    }
  },
  recovery: function () {//中途结束编辑，恢复原来

  },
  showSplitMergeTool: function () {
    this.init()
    map.addControl(this.draw)
  },
  removeSplitMergeTool: function () {
    map.removeControl(this.draw)
  }
}


/** 编辑Start *****************************************************************/
//获取编辑的要素
let editPoints//编辑的点图层

let editMovePoint = ''  //获取移动的点

map.edit = {
  status: false,
  mode: 'normal',//编辑模式  normal正常,clip分割,union联合，buffer缓冲
  style: function (style) {//设置编辑的样式
    this.paint = style
  },
  open: function () { //1.打开编辑
    if (!this.status) {
      this.status = true
      this.init()
    }
    if (map.draw.layerId == undefined || map.draw.layerId == '') {
      map.draw.layerId = 'drawFeaturesPolygon'
    }//没有默认编辑层则指定默认
    map.draw.init()//初始化绘制资源
    map.on('click', this.click)
  },
  clip: function () {//分割
    if (this.mode != 'clip') {
      this.mode = 'clip'
      map.draw.drawFeature = undefined
      map.on('click', map.draw.layerId, this.clipClick)//选中要素事件
    } else {
      this.mode = 'normal'
      map.off('click', map.draw.layerId, this.clipClick)//选中要素事件
      map.off('click', this.edit.clipLine) //关闭画线事件
      map.off('mousemove', this.edit.clipLineMousemove)//关闭画线事件
      map.off('dblclick', this.edit.clipLineDblclick)//关闭画线事件
    }
    this.cancel()
  },
  clipClick: function (e) {
    if (this.draw.drawFeature) {
      return
    }//如果已经选中了要素
    //获取选中的要素
    const editLayer = [this.draw.layerId]

    if (this.draw.layerId == 'drawFeaturesPolygon') {
      editLayer.push('drawFeaturesLineString')
    }
    const features = map.queryRenderedFeatures([[e.point.x - 5, e.point.y - 5], [e.point.x + 5, e.point.y + 5]], { layers: editLayer })

    if (features.length <= 0) {
      return
    }

    map.getSource(map.getLayer(this.draw.layerId).source)._data.features.forEach(f => {
      if (f.properties.id == features[0].properties.id) {
        this.draw.drawFeature = JSON.parse(JSON.stringify(f))
        map.getSource('selectedClip').setData(this.draw.drawFeature)
        map.off('click', map.draw.layerId, this.edit.clipClick)//取消选中事件
        this.clickTime = 0    //记录单击时间，用于判断是否双击
        map.on('click', this.edit.clipLine) //开启画线事件
        map.on('dblclick', this.edit.clipLineDblclick) //开启画线事件
        map.on('mousemove', this.edit.clipLineMousemove)//开启画线事件
        map.doubleClickZoom.disable()  // 禁用双击放大事件
      }
    })
  },
  clipLine: function (e) {
    const id = new Date().getTime()

    if (this.edit.clickTime == 0 || id - this.edit.clickTime < 300) {
      return this.edit.clickTime = id
    }//记录点击时间
    let data = map.getSource('clip')._data

    if (data === null || data.features.length == 0) {
      data = turf.featureCollection([turf.lineString([[e.lngLat.lng, e.lngLat.lat], [e.lngLat.lng, e.lngLat.lat]], { id: id })])
    } else {
      data.features[0].geometry.coordinates.splice(data.features[0].geometry.coordinates.length - 1, 1, [e.lngLat.lng, e.lngLat.lat], [e.lngLat.lng, e.lngLat.lat])
    }
    map.getSource('clip').setData(data)
  },
  clipLineMousemove: function (e) {
    const data = map.getSource('clip')._data

    if (data === null || data.features.length == 0) {
      return
    }
    data.features[0].geometry.coordinates.splice(data.features[0].geometry.coordinates.length - 1, 1, [e.lngLat.lng, e.lngLat.lat])
    map.getSource('clip').setData(data)
  },
  clipLineDblclick: function (e) {
    if (length(map.getSource('clip')._data.features[0]) == 0) {
      return
    }//防止一开始就进行双击事件
    map.off('click', this.edit.clipLine) //关闭画线事件
    map.off('mousemove', this.edit.clipLineMousemove)//关闭画线事件
    map.off('dblclick', this.edit.clipLineDblclick)//关闭画线事件
    window.setTimeout(() => {
      map.doubleClickZoom.enable()
    }) // 取消双击放大事件

    this.drawFeatures.push(indoorRotate(feature, true))

    const df = JSON.parse(JSON.stringify(map.draw.drawFeature))

    const clippedPolygon = geoUtil.polygonClipByLine(map.draw.drawFeature, map.getSource('clip')._data.features[0])

    console.log(clippedPolygon)
    for (let i = 0; i < clippedPolygon.features.length; i++) {
      const cli = JSON.parse(JSON.stringify(clippedPolygon.features[i]))

      cli.properties = JSON.parse(JSON.stringify(df.properties))
      if (cli.properties['operationType']) {//存在操作类型，说明是新增的要素的拆分
        console.log('有值', cli.properties['operationType'])
        cli.properties['id'] = new Date().getTime()
        cli.properties['operationType'] = 'add'
        if (map.draw.mapid != undefined && map.draw.mapid != '') {
          cli.properties['mapid'] = map.draw.mapid
        }
        map.draw.drawFeatures.push(indoorRotate(cli, true))//绘制要素放到集合里
        const source = map.getSource(map.getLayer(map.draw.layerId).source)._data

        source.features.push(cli)
        map.getSource(map.getLayer(map.draw.layerId).source).setData(source)

      } else {//不存在操作类型，说明是原有要素的拆分,默认把第一个当成新增要素
        if (i == 0) {
          cli.properties['id'] = new Date().getTime()
          cli.properties['operationType'] = 'add'
          if (map.draw.mapid != undefined && map.draw.mapid != '') {
            cli.properties['mapid'] = map.draw.mapid
          }
          map.draw.drawFeatures.push(indoorRotate(cli, true))//绘制要素放到集合里
          const source = map.getSource(map.getLayer(map.draw.layerId).source)._data

          source.features.push(cli)
          map.getSource(map.getLayer(map.draw.layerId).source).setData(source)
        } else {
          cli.properties['operationType'] = 'update'
          map.draw.drawFeature = JSON.parse(JSON.stringify(cli))
          map.edit.updateData()
        }
      }
    }
    map.edit.cancel()
  },
  union: function () {//联合
    if (this.mode != 'union') {
      this.mode = 'union'//
    } else {
      this.mode = 'normal'//
    }
    this.cancel()//
  },
  buffer: function () {//缓冲
    if (this.mode != 'buffer') {
      this.mode = 'buffer'//
    } else {
      this.mode = 'normal'//
    }
    this.cancel()//
  },
  //初始化编辑资源
  init: function () {//2.初始化编辑层
    //判断是否有编辑层，没有则添加
    if (!map.getSource('editFeature') || !map.getSource('editPoints')) {
      map.addSource('editFeature', { 'type': 'geojson', 'data': null })
      map.addSource('editPoints', { 'type': 'geojson', 'data': null })
      //面层
      map.addLayer({
        id: 'editFeature',
        type: 'fill',
        source: 'editFeature',
        paint: {
          'fill-color': 'blue',
          'fill-opacity': 0.2 // 透明度
        },
        filter: ['in', '$type', 'Polygon']
      })
      //面层的线样式
      map.addLayer({
        id: 'editFeaturesLine',
        type: 'line',
        source: 'editFeature',
        layout: {
          'line-cap': 'round',
          'line-join': 'round'
        },
        paint: {
          'line-color': '#ff0000',
          'line-width': 2
        },
        filter: ['in', '$type', 'Polygon']
      })
      //线类型
      map.addLayer({
        id: 'editFeatureLineString',
        type: 'line',
        source: 'editFeature',
        layout: {
          'line-cap': 'round',
          'line-join': 'round'
        },
        paint: {
          'line-color': '#ff0000',
          'line-width': 2
        },
        filter: ['in', '$type', 'LineString']
      })
      map.addLayer({
        id: 'editPoints',
        type: 'circle',
        source: 'editPoints',
        paint: {
          'circle-radius': 7,
          'circle-color': ['match',
            ['get', 'type'],
            'centerPoint', 'white',
            '#ff0000'
          ]
        }
      })
    }
    if (!map.getSource('selectedClip') || !map.getSource('clip')) {
      map.addSource('selectedClip', { 'type': 'geojson', 'data': null })
      //面层
      map.addLayer({
        id: 'selectedClip',
        type: 'fill',
        source: 'selectedClip',
        paint: {
          'fill-color': 'blue',
          'fill-opacity': 0.2 // 透明度
        },
        filter: ['in', '$type', 'Polygon']
      })
      //面层的线样式
      map.addLayer({
        id: 'selectedClipLine',
        type: 'line',
        source: 'selectedClip',
        layout: {
          'line-cap': 'round',
          'line-join': 'round'
        },
        paint: {
          'line-color': '#ff0000',
          'line-width': 2
        },
        filter: ['in', '$type', 'Polygon']
      })
      map.addSource('clip', { 'type': 'geojson', 'data': null })
      //线要素的 线样式
      map.addLayer({
        id: 'clipLineString',
        type: 'line',
        source: 'clip',
        layout: {
          'line-cap': 'round',
          'line-join': 'round'
        },
        paint: {
          'line-color': '#ff0000',
          'line-width': 2
        },
        filter: ['in', '$type', 'LineString']
      })
      //线要素的 点样式
      map.addLayer({
        id: 'clipPoint',
        type: 'circle',
        source: 'clip',
        paint: {
          'circle-radius': 5,
          'circle-color': '#ff0000'
        },
        filter: ['in', '$type', 'LineString']
      })
    }

    map.on('mouseenter', 'editPoints', this.mouseenter)
    map.on('mouseleave', 'editPoints', this.mouseleave)
    map.on('mousedown', 'editPoints', this.mousedown)
    map.on('contextmenu', 'editPoints', this.contextmenu)
    //编辑层右键
    //map.on('contextmenu','editFeature', this.deleteFeature);
  },
  click: function (e) {//3.点击选中要编辑的要素
    if (map.draw.status || map.edit.mode != 'normal') {
      return
    }//如果正在绘制时，编辑不执行;不是正常编辑的模式，这里不执行(如拆分、合并等)
    //如果是点在了正在编辑的图形上，正常操作
    const editLayers = map.queryRenderedFeatures(e.point, { layers: ['editFeature', 'editFeatureLineString', 'editPoints'] })

    if (editLayers.length > 0 && this.draw.drawFeature && this.draw.drawFeature.properties.id == editLayers[0].properties.id) {
      return
    }

    //选中编辑的要素
    const editLayer = [this.draw.layerId]

    console.log(1, editLayer)

    if (this.draw.layerId == 'drawFeaturesPolygon') {
      editLayer.push('drawFeaturesLineString')
    }
    const features = map.queryRenderedFeatures([[e.point.x - 5, e.point.y - 5], [e.point.x + 5, e.point.y + 5]], { layers: editLayer })

    if (features.length == 0) {
      return this.edit.cancel()
    }//如果点中了空白区域
    //获取选中的要素
    map.getSource(map.getLayer(this.draw.layerId).source)._data.features.forEach(f => {
      if (f.properties.id == features[0].properties.id) {
        this.draw.drawFeature = JSON.parse(JSON.stringify(f))
      }//pdf服务读不到gid只有用id
    })
    //获取中心点
    editPoints = { 'type': 'FeatureCollection', 'features': [] }
    //根据不同要素类型解析坐标
    let coord

    switch (this.draw.drawFeature.geometry.type) {
    case 'Polygon':
      coord = this.draw.drawFeature.geometry.coordinates[0]
      break
      // case 'MultiPolygon':

      //     break;
      // case 'LineString':

      //   break;
      // case 'MultiLineString':

      //   break;
    default:
      coord = this.draw.drawFeature.geometry.coordinates
      break
    }

    for (let j = 0; j < coord.length - 1; j++) {
      const prevPoint = turf.point(coord[j], { 'id': new Date().getTime() + '-' + j, 'type': '' })

      const midpoint1 = midpoint(prevPoint, turf.point(coord[j + 1]))

      midpoint1.properties = { 'id': new Date().getTime() + '--' + j, 'type': 'centerPoint' }//type：centerPoint 代表是每段的中心点
      editPoints.features.push(prevPoint)
      editPoints.features.push(midpoint1)
    }
    //线类型时，实际点数比中点个数多一个，把最后一个补充上
    if (this.draw.drawFeature.geometry.type == 'LineString') {
      const lastPoint = turf.point(coord[coord.length - 1], { 'id': new Date().getTime() + '-' + (coord.length - 1), 'type': '' })

      editPoints.features.push(lastPoint)
    }
    map.getSource('editFeature').setData(this.draw.drawFeature)
    map.getSource('editPoints').setData(editPoints)
  },
  mouseenter: function (e) {//4-.编辑中识别到鼠标在编辑的点上
    map.getCanvasContainer().style.cursor = 'move'
  },
  mouseleave: function (e) { //4-.编辑中鼠标离开了编辑的点
    map.getCanvasContainer().style.cursor = ''
  },
  mousedown: function (e) {//4-.编辑中鼠标按下事件
    if (e.originalEvent.which != 1) {
      return
    }//判断是不是左键按下
    editMovePoint = e.features[0]
    e.preventDefault()
    map.getCanvasContainer().style.cursor = 'grab'
    map.on('mousemove', this.edit.mousemove)
    map.once('mouseup', this.edit.mouseup)
  },
  mouseup: function (e) {//4-.编辑时鼠标抬起 针对editPoints层(操作的点类型)，
    map.getCanvasContainer().style.cursor = ''
    map.off('mousemove', this.edit.mousemove)
    map.off('touchmove', this.edit.mousemove)
    editMovePoint = ''
  },
  contextmenu: function (e) {//4-.编辑中右键事件，针对editPoints层(操作的点类型)，
    //右键的是面类型的正常拐点
    const coords = []

    let len = editPoints.features.length

    if (e.features[0].properties.type != '') {
      return
    }//不是正常拐点则返回
    if (this.draw.drawFeature.geometry.type == 'Polygon' && len == 6) {
      return
    }
    if (this.draw.drawFeature.geometry.type == 'LineString' && len == 3) {
      return
    }
    for (let i = 0; i < len; i++) {
      if (editPoints.features[i].properties.id == e.features[0].properties.id) {
        if (this.draw.drawFeature.geometry.type == 'Polygon') {
          if (i == 0) {
            editPoints.features[len - 1].geometry = midpoint(editPoints.features[len - 2], editPoints.features[i + 2]).geometry
          } else if (i == len - 2) {
            editPoints.features[len - 3].geometry = midpoint(editPoints.features[len - 4], editPoints.features[0]).geometry
          } else {
            editPoints.features[i - 1].geometry = midpoint(editPoints.features[i - 2], editPoints.features[i + 2]).geometry
          }
          editPoints.features.splice(i, 2)//删除当前拐点和下一个中点
        }
        if (this.draw.drawFeature.geometry.type == 'LineString') {
          if (i != 0 && i != len - 1) {
            editPoints.features[i - 1].geometry = midpoint(editPoints.features[i - 2], editPoints.features[i + 2]).geometry
          }
          editPoints.features.splice(i == len - 1 ? len - 2 : i, 2)//删除当前拐点+下一个中点或当前点+前一个点
        }
        len = editPoints.features.length
      }
    }
    for (let i = 0; i < len; i++) {
      if (editPoints.features[i].properties.type == '') {
        coords.push(editPoints.features[i].geometry.coordinates)
      }
    }

    if (this.draw.drawFeature.geometry.type == 'Polygon') {
      coords.push(coords[0])
    }
    this.draw.drawFeature.geometry.coordinates = this.draw.drawFeature.geometry.type == 'Polygon' ? [coords] : coords
    map.getSource('editFeature').setData(this.draw.drawFeature)
    map.getSource('editPoints').setData(editPoints)
    this.edit.updateData()
  },
  mousemove: function (e) {//4-.编辑时鼠标按下时移动 针对editPoints层(操作的点类型)，
    e.lngLat = map.catch.lngLat(e)//捕捉(如果开启了则调用，未开启则不调用)
    map.getCanvasContainer().style.cursor = 'grabbing'
    const coords = [], len = editPoints.features.length

    //面要素
    if (this.draw.drawFeature.geometry.type == 'Polygon') {
      if (editMovePoint.properties.type == '') {//移动的是正常拐点
        for (let i = 0; i < len; i++) {
          if (editPoints.features[i].properties.id == editMovePoint.properties.id) {
            editPoints.features[i].geometry.coordinates = [e.lngLat.lng, e.lngLat.lat] //把移动的坐标赋值到实际点位上
            //更新相邻的两个中点(如果是第一个点使用len-1)
            editPoints.features[i == 0 ? len - 1 : i - 1].geometry = midpoint(editPoints.features[i == 0 ? len - 2 : i - 2], editPoints.features[i]).geometry
            editPoints.features[i + 1].geometry = midpoint(editPoints.features[i == len - 2 ? 0 : i + 2], editPoints.features[i]).geometry
          }
          if (editPoints.features[i].properties.type == '') {
            coords.push(editPoints.features[i].geometry.coordinates)
          }
        }
      } else {//移动的是线段中点 centerPoint
        moveMidpoint()
      }
      coords.push(coords[0])
      this.draw.drawFeature.geometry.coordinates[0] = coords
    }
    //线要素
    if (this.draw.drawFeature.geometry.type == 'LineString') {
      if (editMovePoint.properties.type == '') {//移动的是正常拐点
        for (let i = 0; i < len; i++) {
          if (editPoints.features[i].properties.id == editMovePoint.properties.id) {
            //把移动的坐标赋值到实际点位上
            editPoints.features[i].geometry.coordinates = [e.lngLat.lng, e.lngLat.lat]
            //更新相邻的两个中点(如果是第一个点使用len-1)
            if (i == 0) {
              editPoints.features[i + 1].geometry = midpoint(editPoints.features[i], editPoints.features[i + 2]).geometry
            } else if (i == len - 1) {
              editPoints.features[i - 1].geometry = midpoint(editPoints.features[i - 2], editPoints.features[i]).geometry
            } else {
              editPoints.features[i - 1].geometry = midpoint(editPoints.features[i - 2], editPoints.features[i]).geometry
              editPoints.features[i + 1].geometry = midpoint(editPoints.features[i], editPoints.features[i + 2]).geometry
            }
          }
          if (editPoints.features[i].properties.type == '') {
            coords.push(editPoints.features[i].geometry.coordinates)
          }
        }
      } else {//移动的是线段中点 centerPoint
        moveMidpoint()
      }
      this.draw.drawFeature.geometry.coordinates = coords
    }
    //移动中点
    function moveMidpoint() {
      for (let i = 0; i < editPoints.features.length; i++) {
        if (editPoints.features[i].properties.id == editMovePoint.properties.id) {
          editPoints.features[i].properties.type = ''//把选中的中点转为正常拐点
          editMovePoint = editPoints.features[i]//转正拐点赋给移动点
          const prevMidpoint = midpoint(editPoints.features[i - 1], editPoints.features[i])

          prevMidpoint.properties = { 'id': new Date().getTime() + '--' + i, 'type': 'centerPoint' }
          //后一个线段的中点
          const nextMidpoint = midpoint(editPoints.features[i], editPoints.features[i + 1 == editPoints.features.length ? 0 : i + 1])

          nextMidpoint.properties = { 'id': new Date().getTime() + '-=' + i, 'type': 'centerPoint' }
          editPoints.features.splice(i + 1, 0, nextMidpoint)
          editPoints.features.splice(i, 0, prevMidpoint)
          i = editPoints.features.length//跳出循环
        }
      }
      editPoints.features.forEach(e => {
        if (e.properties.type == '') {
          coords.push(e.geometry.coordinates)
        }
      })
    }
    //sq2021-8-11map.getSource('editFeature').setData(this.edit.editFeature);
    map.getSource('editFeature').setData(this.draw.drawFeature)
    map.getSource('editPoints').setData(editPoints)
    map.edit.updateData()
  },
  updateData: function () {//4-1.实时更新编辑的要素  右键使用，移动使用，保存使用
    //集合里没有新选中的要素的话就放进去s
    let exist = false

    for (let i = 0; i < map.draw.drawFeatures.length; i++) {
      if (map.draw.drawFeatures[i].properties.id == map.draw.drawFeature.properties.id) {
        map.draw.drawFeatures[i] = indoorRotate(map.draw.drawFeature, true)
        i = map.draw.drawFeatures.length//跳出循环
        exist = true
      }
    }
    if (!exist) { //不存在
      if (!map.draw.drawFeature.properties.operationType) {
        map.draw.drawFeature.properties['operationType'] = 'update'
      }//如果要素是原有的，操作类型是更新
      map.draw.drawFeatures.push(indoorRotate(map.draw.drawFeature, true))//绘制要素放到集合里
    }
    //集合里没有新选中的要素的话就放进去e

    const sourceId = map.getLayer(map.draw.layerId).source

    const source = map.getSource(sourceId)._data

    for (let i = 0; i < source.features.length; i++) {
      if (source.features[i].properties.id == map.draw.drawFeature.properties.id) {
        source.features[i] = map.draw.drawFeature
        map.getSource(sourceId).setData(source)
        i = source.features.length
      }
    }
  },
  deleteFeature: function () {//4-.正在编辑的要素，删除,当前是右键调用
    if (map.draw.drawFeature == undefined) {
      return
    }

    let exist = false

    for (let i = 0; i < map.draw.drawFeatures.length; i++) {
      if (map.draw.drawFeatures[i].properties.id == map.draw.drawFeature.properties.id) {
        if (map.draw.drawFeatures[i].properties.operationType == 'add') {
          map.draw.drawFeatures.splice(i, 1)
        } //删除新绘的要素，因为库没有，所以可直接删除
        else if (map.draw.drawFeatures[i].properties.operationType == 'update') {
          map.draw.drawFeatures[i].properties.operationType = 'delete'
        }//删除已有的要素，update改为delete,用于删除库里数据
        i = map.draw.drawFeatures.length//跳出循环
        exist = true
      }
    }
    if (!exist) { //不存在
      if (!map.draw.drawFeature.properties.operationType) {
        map.draw.drawFeature.properties['operationType'] = 'delete'
      }//如果要素是原有的，操作类型是删除
      map.draw.drawFeatures.push(indoorRotate(map.draw.drawFeature, true))//绘制要素放到集合里
    }

    //如果右键的要素是绘制的集合
    // for(var i=0;i<map.draw.drawFeatures.length;i++){
    //   if(map.draw.drawFeature.properties.id==map.draw.drawFeatures[i].properties.id) {
    //     if(map.draw.drawFeatures[i].properties.operationType=='add'){ map.draw.drawFeatures.splice(i,1);} //删除新绘的要素，因为库没有，所以可直接删除
    //     else if(map.draw.drawFeatures[i].properties.operationType=='update') { map.draw.drawFeatures[i].properties.operationType='delete'; }//删除已有的要素，update改为delete,用于删除库里数据
    //     i=map.draw.drawFeatures.length;//跳出循环
    //   };
    // }
    //更新资源层
    const sourceId = map.getLayer(map.draw.layerId).source

    const source = map.getSource(sourceId)._data

    for (let i = 0; i < source.features.length; i++) {
      if (source.features[i].properties.id == map.draw.drawFeature.properties.id) {
        source.features.splice(i, 1)
        map.getSource(sourceId).setData(source)
        this.cancel()
        i = source.features.length
      }
    }
  },
  updateFeature: function () {//4-.正在编辑的要素，更新属性
    if (map.draw.drawFeature == undefined) {
      return
    }
    this.updateData()//
    this.cancel()
  },
  cancel: function () {//4-编辑取消
    if (map.getSource('editFeature')) {
      map.getSource('editFeature').setData({ 'type': 'FeatureCollection', 'features': [] })
    }
    if (map.getSource('editPoints')) {
      map.getSource('editPoints').setData({ 'type': 'FeatureCollection', 'features': [] })
    }
    if (map.getSource('selectedClip')) {
      map.getSource('selectedClip').setData({ 'type': 'FeatureCollection', 'features': [] })
    }
    if (map.getSource('clip')) {
      map.getSource('clip').setData({ 'type': 'FeatureCollection', 'features': [] })
    }
    map.draw.drawFeature = undefined
  },
  close: function () {//5关闭编辑
    this.status = false
    map.off('click', this.click)
    if (map.getLayer('editFeature')) {
      map.removeLayer('editFeature')
    }
    if (map.getLayer('editFeaturesLine')) {
      map.removeLayer('editFeaturesLine')
    }
    if (map.getLayer('editFeatureLineString')) {
      map.removeLayer('editFeatureLineString')
    }
    if (map.getLayer('editPoints')) {
      map.removeLayer('editPoints')
    }
    if (map.getSource('editFeature')) {
      map.removeSource('editFeature')
    }
    if (map.getSource('editPoints')) {
      map.removeSource('editPoints')
    }

    if (map.getLayer('selectedClip')) {
      map.removeLayer('selectedClip')
    }
    if (map.getLayer('selectedClipLine')) {
      map.removeLayer('selectedClipLine')
    }
    if (map.getLayer('clipLineString')) {
      map.removeLayer('clipLineString')
    }
    if (map.getLayer('clipPoint')) {
      map.removeLayer('clipPoint')
    }
    if (map.getSource('selectedClip')) {
      map.removeSource('selectedClip')
    }
    if (map.getSource('clip')) {
      map.removeSource('clip')
    }


    map.off('mouseenter', this.mouseenter)
    map.off('mouseleave', this.mouseleave)
    map.off('mousedown', this.mousedown)
  },
  recovery: function () {//中途结束编辑，恢复原来

  }
}

/** 编辑End */
//图形处理工具
var geoUtil = {
  /**
     * 合并多边形
     */
  unionPolygon: function (polygons) {
    let polygon = polygons[0]

    for (let i = 0; i < polygons.length; i++) {
      polygon = union(polygon, polygons[i])
    }
    return polygon
  },
  /**
     * 线分割面
     * 面类型只能是polygon 但可以是环
     * 注:线与多边形必须有两个交点
     */
  polygonClipByLine: function (polygon, clipLine) {
    if (polygon.geometry.type === 'Polygon') {
      const polyLine = polygonToLine(polygon)

      if (polyLine.geometry.type === 'LineString') { // 切割普通多边形
        return this._singlePolygonClip(polyLine, clipLine)
      } else if (polyLine.geometry.type === 'MultiLineString') { //切割环
        return this._multiPolygonClip(polyLine, clipLine)
      }
    } else if (polygon.geometry.type === 'MultiPolygon') {
      // 若输入的多边形类型为Multipolygon则拆分成多个Polygon
      const polygons = this.multiPolygon2polygons(polygon)

      let clipPolygon = null

      let clipPolygonIndex = -1
      // 获取MultiPolygon中与切割线相交的多边形（有且只能有一个多边形相交2个交点）

      polygons.forEach(function (polygon, index) {
        const polyLine = polygonToLine(polygon)

        if (lineIntersect(polyLine, clipLine).features.length === 2) {
          if (!clipPolygon) {
            clipPolygon = polygon
            clipPolygonIndex = index
          } else {
            throw { state: '裁剪失败', message: 'MultiPolygon只能有一个多边形与切割线存在交点' }
          }
        }
      })
      if (clipPolygonIndex !== -1) {
        polygons.splice(clipPolygonIndex, 1)
        return turf.featureCollection(polygons.concat(this.polygonClipByLine(clipPolygon, clipLine).features))
      }
      throw { state: '裁剪失败', message: 'MultiPolygon与切割线无交点' }


    } else {
      throw { state: '裁剪失败', message: '输入的多边形类型为错误' }
    }
  },

  _singlePolygonClip: function (polyLine, clipLine) {
    // 获得裁切点
    const intersects = lineIntersect(polyLine, clipLine)

    if (intersects.features.length !== 2) {
      throw { state: '裁剪失败', message: '切割线与多边形交点应该为2个,当前交点个数为' + intersects.features.length }
    }
    // 检查切割线与多边形的位置关系 （切割线的起点和终点不能落在多边形内部）
    const clipLineLength = clipLine.geometry.coordinates.length

    const clipLineStartPoint = turf.point(clipLine.geometry.coordinates[0])

    const clipLineEndPoint = turf.point(clipLine.geometry.coordinates[clipLineLength - 1])

    const polygon = turf.polygon([polyLine.geometry.coordinates])

    if (booleanPointInPolygon(clipLineStartPoint, polygon) || booleanPointInPolygon(clipLineEndPoint, polygon)) {
      throw { state: '裁剪失败', message: '切割线起点或终点不能在 裁剪多边形内部' }
    }
    // 通过裁切点 分割多边形（只能获得多边形的一部分）
    const slicedPolyLine = lineSlice(intersects.features[0], intersects.features[1], polyLine)
    // 裁剪线分割 保留多边形内部部分

    const slicedClipLine = lineSlice(intersects.features[0], intersects.features[1], clipLine)
    // 重新拼接多边形 存在 对接的问题 所以先进行判断 如何对接裁剪的多边形和裁剪线

    const resultPolyline1 = this.connectLine(slicedPolyLine, slicedClipLine)
    // 闭合线 来构造多边形

    resultPolyline1.geometry.coordinates.push(resultPolyline1.geometry.coordinates[0])
    const resultPolygon1 = lineToPolygon(resultPolyline1)
    // 构造切割的另一面多边形

    const firstPointOnLine = this.isOnLine(turf.point(polyLine.geometry.coordinates[0]), slicedPolyLine)

    const pointList = []

    if (firstPointOnLine) {
      for (var i = 0; i < polyLine.geometry.coordinates.length; i++) {
        var coordinate = polyLine.geometry.coordinates[i]

        if (!this.isOnLine(turf.point(coordinate), slicedPolyLine)) {
          pointList.push(coordinate)
        }
      }
    } else {
      let skipNum = 0 // 记录前面被跳过的点的个数

      let isStartPush = false

      for (var i = 0; i < polyLine.geometry.coordinates.length; i++) {
        var coordinate = polyLine.geometry.coordinates[i]

        if (!this.isOnLine(turf.point(coordinate), slicedPolyLine)) {
          if (isStartPush) {
            pointList.push(coordinate)
          } else {
            skipNum++
          }

        } else {
          isStartPush = true
        }
      }
      // 将前面跳过的点补充到 点数组中
      for (var i = 0; i < skipNum; i++) {
        pointList.push(polyLine.geometry.coordinates[i])
      }
    }
    const slicedPolyLine_2 = turf.lineString(pointList)

    const resultPolyline2 = this.connectLine(slicedPolyLine_2, slicedClipLine)
    // 闭合线 来构造多边形

    resultPolyline2.geometry.coordinates.push(resultPolyline2.geometry.coordinates[0])
    const resultPolygon2 = lineToPolygon(resultPolyline2)
    // 返回面要素集

    return turf.featureCollection([
      resultPolygon1,
      resultPolygon2
    ])

  },

  _multiPolygonClip: function (polyLine, clipLine) {
    // 将环 多边形分割成 内部逆时针多边形+外部多边形
    let outPolyline
    const insidePolylineList = []

    for (var i = 0; i < polyLine.geometry.coordinates.length; i++) {
      const splitPolyline = turf.lineString(polyLine.geometry.coordinates[i])

      if (turf.booleanClockwise(splitPolyline)) {
        if (outPolyline) {
          throw { state: '裁剪失败', message: '出现了两个外部多边形无法处理' }
        } else {
          outPolyline = splitPolyline
        }
      } else {
        const intersects = lineIntersect(splitPolyline, clipLine)

        if (intersects.features.length > 0) {
          throw { state: '裁剪失败', message: '切割线不能与内环有交点' }
        }
        insidePolylineList.push(splitPolyline)
      }
    }
    const resultCollection = this._singlePolygonClip(outPolyline, clipLine)

    for (var i = 0; i < resultCollection.features.length; i++) {
      for (let j = 0; j < insidePolylineList.length; j++) {
        const startPoint = turf.point(insidePolylineList[j].geometry.coordinates[0])

        if (turf.booleanPointInPolygon(startPoint, resultCollection.features[i])) {
          resultCollection.features[i] = turf.mask(resultCollection.features[i], lineToPolygon(insidePolylineList[j]))
        }
      }
    }
    return resultCollection
  },

  /**
     * 连接两条线
     * 方法会将两条线段最近的一段直接连接
     */
  connectLine: function (line1, line2) {
    const line2_length = line2.geometry.coordinates.length

    const line1_startPoint = line1.geometry.coordinates[0]

    const line2_startPoint = line2.geometry.coordinates[0]

    const line2_endPoint = line2.geometry.coordinates[line2_length - 1]

    const pointList = []
    // 获取line1 所有点坐标

    for (var i = 0; i < line1.geometry.coordinates.length; i++) {
      var coordinate = line1.geometry.coordinates[i]

      pointList.push(coordinate)
    }

    // 判断两条线的 起点是否接近，如果接近 逆转line2线 进行连接
    if (distance(line1_startPoint, line2_startPoint) < distance(line1_startPoint, line2_endPoint)) {
      line2.geometry.coordinates = line2.geometry.coordinates.reverse()
    }
    for (var i = 0; i < line2.geometry.coordinates.length; i++) {
      var coordinate = line2.geometry.coordinates[i]

      pointList.push(coordinate)
    }
    return turf.lineString(pointList)
  },

  /**
     * 判断点是否在线里面
     * 注：线组成的坐标对比
     */
  isOnLine: function (point, line) {
    for (let i = 0; i < line.geometry.coordinates.length; i++) {
      const coordinate = line.geometry.coordinates[i]

      if (point.geometry.coordinates[0] === coordinate[0] && point.geometry.coordinates[1] === coordinate[1]) {
        return true
      }
    }
    return false
  },

  /**
     * 获得两条线交点
     */
  getIntersectPoints: function (line1, line2) {
    return lineIntersect(line1, line2)
  },
  /**
     * multiPolygon转polygons,不涉及属性
     */
  multiPolygon2polygons: function (multiPolygon) {
    if (multiPolygon.geometry.type !== 'MultiPolygon') {
      return
    }
    const polygons = []

    multiPolygon.geometry.coordinates.forEach((item) => {
      const polygon = {
        type: 'Feature',
        properties: {},
        geometry: {
          type: 'Polygon',
          coordinates: []
        }
      }

      polygon.geometry.coordinates = item
      polygons.push(polygon)
    })
    return polygons
  },
  /**
     * polygons转multiPolygon,不涉及属性，只输出属性为{}
     * 考虑polygons中就存在多面的情况
     */
  polygons2MultiPolygon: function (geoJson) {
    const newGeoJson = {
      type: 'FeatureCollection',
      features: [{ geometry: { coordinates: [], type: 'MultiPolygon' }, type: 'Feature', properties: {} }]
    }

    geoJson.features.forEach((item) => {
      if (item.geometry.type === 'Polygon') {
        newGeoJson.features[0].geometry.coordinates.push(item.geometry.coordinates)
      } else {
        item.geometry.coordinates.forEach((item) => {
          newGeoJson.features[0].geometry.coordinates.push(item)
        })
      }
    })
    return newGeoJson
  }
}

